package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;


//找出出现至少三次的最长特殊子字符串
public class Lc2981 {


    public int maximumLength(String s) {

        HashMap<String, Integer> map = new HashMap<>();

        int i = 0, j = 0;
        while (i <= j && j < s.length()) {
            if (s.charAt(i) == s.charAt(j)) {
                String temp = s.substring(i, j + 1);
                map.put(temp, map.getOrDefault(temp, 0) + 1);
                j++;
            }
            else {
                if (i + 1 == j) {
                    i++;
                    continue;
                }
                int n = j - i;
                i++;
                while (i != j) {
                    String temp = s.substring(i, j);
                    map.put(temp, map.get(temp) + n - j + i);
                    i++;
                }
            }
        }
        int n = j - i;
        i++;
        while (i != j ) {
            String temp = s.substring(i, j);
            map.put(temp, map.get(temp) + n - j + i);
            i++;
        }

        ArrayList<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.length() - o1.length();
            }
        });


        int ans = -1;
        for (String str: list) {
            if (str.length() <= ans)
                return ans;
            if (map.get(str) >= 3) {
                return str.length();
            }
        }
        return ans;
    }


    public static void main(String[] args) {
        Lc2981 lc2981 = new Lc2981();
        System.out.println(lc2981.maximumLength("aaaa"));
    }











}
